package com.trust.pams.dao.service.impl;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.trust.pams.dao.service.EsPamsPuoteIdDao;
import com.trust.pams.dao.service.EsPamsSvnDao;
import com.trust.pams.model.es.QuoteEsSearch;
import com.trust.pams.model.es.SvnEsSearch;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Repository
public class EsPamsSvnDaoImpl  implements EsPamsSvnDao {

    private static final Logger log = LoggerFactory.getLogger(EsPamsPuoteIdDaoImpl.class);

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean batchAddDocument(List<SvnEsSearch> itemEsSearchList, String indexName) {
        BulkRequest bulkRequest = new BulkRequest();
        itemEsSearchList.stream().forEach(item->{
            bulkRequest.add(new IndexRequest(indexName + "__pams_svn").source(JSON.toJSONString(item), XContentType.JSON));
        });

        try{
            BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (responses.status().getStatus()== HttpStatus.HTTP_OK){
                return true;
            }
        }catch (IOException e){
            log.error("batchIndex exception",e);
        }
        return false;
    }

    @Override
    public long dleteDocument(String id, String indexName) {
        //参数为索引名，可以不指定，可以一个，可以多个
        DeleteByQueryRequest request = new DeleteByQueryRequest(indexName + "__pams_svn");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.queryStringQuery(id));
        request.setQuery(boolQueryBuilder);
        try {
            BulkByScrollResponse response = restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
            return response.getStatus().getUpdated();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
